package com.itcm.springsecuritydemo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author jinchengming
 * @version 1.0.0
 * @date 2022/10/17 15:43
 */

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1. 查询数据库判断用户是否存在，否则抛出异常：UsernameNotFoundException
        if (!"admin".equals(username)){
            // 模拟数据库查询
            throw new UsernameNotFoundException("用户名不存在！");
        }
        // 2. 根据查询出的信息，构造User（SpringSecurity提供的实现了UserDetails的User类）
        // 这里的password和权限列表 实际开发应该是上一步查询数据库获取的 这里只是模拟
        String password = passwordEncoder.encode("123456");
        return new User(username, password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin,normal,ROLE_admin,ROLE_abc"));
    }
}
